﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using LitJson;


namespace eFrameWork.Customs
{
    public partial class Excel_Templates : System.Web.UI.Page
    {
        public string UserArea = "Application";
        public string act = eParameters.Request("act");
        public string ModelID = eParameters.Request("ModelID");
        public string AppItem = eParameters.Request("AppItem");
        public eUser user;
        public eModel model;


        private string basePath = "";//当前目录
        public string siteid = "";
        public string path = eParameters.QueryString("path");
        string aspxFile = eBase.getAspxFileName();
        string type = eParameters.QueryString("type");
        public string sitefolder = "";
        public string ajax = eParameters.QueryString("ajax");
        public string basefolder = "ExcelTemplates";
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser(eBase.getUserArea(UserArea));
            user.Check();


            eModelInfo customModel = new eModelInfo(user);
            model = customModel.Model;

            siteid = user["siteid"].ToString();
            if (siteid.Length == 0) siteid = eBase.getSiteID();// eConfig.SiteID();
            sitefolder = eConfig.getSiteFolder(siteid);


            basePath = Server.MapPath("~/") + "upload\\" + (sitefolder.Length > 0 ? sitefolder + "\\" : "") + basefolder + "\\";
            //string templatePath = eConfig.getTemplateFolder(siteid);
            //if (templatePath.Length > 0) basePath += templatePath + "\\";


            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
            if (path.Length > 0) basePath += path.Replace("/", "\\") + "\\";
            #region 安全性
            if (act.Length > 0 && (Request.UrlReferrer == null || Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower()))
            {
                //Response.Write("访问未被许可!");
                //Response.End();
            }
            #endregion
            #region 操作
            string filepath = "";
            string oldname = "";
            string newname = "";
            string reurl = "";
            string sql = "";
            DataTable tb;
            string ext = "";
            switch (act)
            {
                case "reload":
                    #region 重新加载
                    JsonData jd = new JsonData();
                    jd.Add("success", "1");
                    jd.Add("errcode", "0");
                    jd.Add("body", getFiles());
                    //jd.Add("table", eBase.encode(eListControl.getControlHTML()));
                    Response.Write(jd.ToJson());
                    Response.End();
                    #endregion
                    break;
                case "upload":
                    #region 上传文件
                    StringBuilder sb = new StringBuilder();
                    string errorString = "";
                    try
                    {
                        string allExt = eConfig.AutoDownExt().ToLower();
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            HttpPostedFile f = Request.Files[i];
                            string fileExt = Path.GetExtension(f.FileName).ToLower();
                            if (allExt.IndexOf(fileExt) == -1)
                            {
                                errorString = "扩展名" + fileExt + "被禁止,上传失败!";
                                break;

                                /*
                                if (ajax == "true")
                                {
                                    eResult.Error("扩展名" + ext + "被禁止,上传失败!");
                                }
                                else
                                {
                                    Response.Write("文件类型不允许上传!");
                                    Response.End();
                                }
                                */
                            }
                            filepath = basePath + Path.GetFileName(f.FileName);
                            f.SaveAs(filepath);
                            getFileHTML(sb, f.FileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.Message);
                        Response.End();
                    }
                    if (errorString.Length > 0)
                    {
                        if (ajax == "true")
                        {
                            eResult.Error(errorString);
                        }
                        else
                        {
                            Response.Write(errorString);
                            Response.End();
                        }
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件上传成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    //Response.Redirect(reurl, true);
                    Response.Write(sb.ToString());
                    Response.End();
                    #endregion
                    break;
                case "save":
                    #region 保存编辑
                    filepath = basePath + eParameters.QueryString("name");
                    if (File.Exists(filepath))
                    {

                        string value = eParameters.Form("value");
                        //value = value.Replace("0x\\r\\n", "\r\n");
                        value = eBase.decode(value);
                        value = value.Replace("\n", "\r\n");

                        //json = new eJson();

                        try
                        {
                            StreamWriter sw = new StreamWriter(filepath, false, Encoding.GetEncoding("UTF-8"));
                            sw.Write(value);
                            sw.Flush();
                            sw.Close();
                            //json.Add("success", "1");
                            //json.Add("message", "保存成功!");
                            eResult.Message(new { success = 1, errcode = "0", message = "保存成功!" });
                        }
                        catch (Exception ex)
                        {
                            //json.Add("success", "0");
                            //json.Add("message", "没有权限!");
                            eResult.Message(new { success = 1, errcode = "-1", message = "没有权限!" });
                        }



                        //eBase.WriteJson(json);
                    }
                    #endregion
                    break;
                case "edit":
                    #region 读取编辑文件数据
                    filepath = basePath + eParameters.QueryString("name");
                    if (File.Exists(filepath))
                    {
                        //json = new eJson();
                        try
                        {
                            Encoding enc = eBase.GetEncoding(filepath);
                            StreamReader sr = new StreamReader(filepath, enc);
                            string content = sr.ReadToEnd();
                            sr.Close();
                            content = HttpUtility.HtmlEncode(content);

                            //json.Add("success", "1");
                            //json.Add("value", eBase.encode(content));
                            eResult.Message(new { success = 1, errcode = "0", message = "保存成功!", value = content });
                        }
                        catch (Exception ex)
                        {
                            //json.Add("success", "0");
                            //json.Add("message", "没有权限!");
                            eResult.Message(new { success = 1, errcode = "-1", message = "没有权限!" });
                        }
                        //eBase.WriteJson(json);
                    }
                    #endregion
                    break;
                case "newfile":
                    #region 新建文件OK
                    ext = Path.GetExtension(eParameters.QueryString("name")).ToLower();
                    if (eConfig.DangerExtensions.Contains(ext))
                    {
                        if (ajax == "true")
                        {
                            eResult.Error("扩展名" + ext + "被禁止,操作失败!");
                        }
                        else
                        {
                            Response.Write("扩展名" + ext + "被禁止,操作失败!");
                            Response.End();
                        }
                    }
                    filepath = basePath + eParameters.QueryString("name");                    
                    if (!File.Exists(filepath))
                    {
                        try
                        {
                            StreamWriter sw = new System.IO.StreamWriter(filepath, false, Encoding.GetEncoding("UTF-8"));
                            sw.Close();
                        }
                        catch (Exception ex)
                        {

                            Response.Write(ex.Message);
                            Response.End();
                        }
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件新建成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "newfolder":
                    #region 添加文件夹OK
                    try
                    {
                        Directory.CreateDirectory(basePath + eParameters.QueryString("name"));
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件夹新建成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "rename":
                    #region 重命名文件、文件夹OK
                    ext = Path.GetExtension(eParameters.QueryString("newname")).ToLower();
                    if (eConfig.DangerExtensions.Contains(ext))
                    {
                        if (ajax == "true")
                        {
                            eResult.Error("扩展名" + ext + "被禁止,操作失败!");
                        }
                        else
                        {
                            Response.Write("扩展名" + ext + "被禁止,操作失败!");
                            Response.End();
                        }
                    }

                    oldname = basePath + eParameters.QueryString("oldname");
                    newname = basePath + eParameters.QueryString("newname");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            Directory.Move(oldname, newname);
                        }
                        if (type == "2")//文件
                        {
                            File.Move(oldname, newname);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("重命名成功!");
                    }

                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "oldname");
                    reurl = eParameters.removeQuery(reurl, "newname");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "bak":
                    #region 备份文件、文件夹OK
                    oldname = basePath + eParameters.QueryString("name");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            newname = oldname + "_bak";
                            if (!Directory.Exists(newname)) eBase.CopyFolder(oldname, newname);
                        }
                        if (type == "2")//文件
                        {
                            newname = oldname + ".bak";
                            if (!File.Exists(newname)) File.Copy(oldname, newname);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件" + (type == "1" ? "夹" : "") + "备份成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "del":
                    #region 删除文件、文件夹OK
                    string tmpPath = basePath + eParameters.QueryString("name");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            if (Directory.Exists(tmpPath)) eBase.DeleteFolder(tmpPath);
                        }
                        if (type == "2")//文件
                        {
                            if (File.Exists(tmpPath)) File.Delete(tmpPath);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件删除成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "zip":
                    #region 压缩OK
                    oldname = basePath + eParameters.QueryString("name");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            newname = oldname + ".zip";
                            FolderToZip(oldname, newname);
                        }
                        if (type == "2")//文件
                        {
                            eFileInfo fi = new eFileInfo(oldname);
                            newname = fi.Path + fi.Name + ".zip";
                            FileToZip(oldname, newname);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件" + (type == "1" ? "夹" : "") + "压缩成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "unzip":
                    #region 解压
                    oldname = basePath + eParameters.QueryString("name");

                    try
                    {
                        new FastZip().ExtractZip(oldname, basePath, "");//覆盖
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件解压成功!");
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "download":
                    #region 下载
                    if (Request.Path != Request.CurrentExecutionFilePath) Response.Redirect(Request.CurrentExecutionFilePath + Request.Url.Query, true);
                    string name = eParameters.QueryString("name");

                     if( Request.UserAgent.ToLower().IndexOf("msie") > -1 ) 
                     {
                         //输出时进行编码，不用接收时解码：Server.UrlEncode(name)
                     }
                    if (name.StartsWith("."))
                    {
                        Response.Write("禁止上级目录下载!");
                        Response.End();
                    }
                    if (eConfig.DangerExtensions.Contains(Path.GetExtension(name).ToLower()))
                    {
                        Response.Write("文件类型不允许下载!");
                        Response.End();
                    }
                    oldname = basePath + name;
                    //eBase.Write(oldname);
                    //eBase.End();

                    FileInfo fileInfo = new FileInfo(oldname);
                    /*
            
                    
                    Response.Clear();
                    Response.ClearContent();
                    Response.ClearHeaders();
                    //HttpUtility.UrlEncode(fileInfo.Name, System.Text.Encoding.UTF8)
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileInfo.Name);
                    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                    Response.AddHeader("Content-Transfer-Encoding", "binary");
                    Response.ContentType = "application/octet-stream";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                    Response.WriteFile(fileInfo.FullName);
                    Response.Flush();
                    Response.End();
                    */
                     Response.ContentType = "application/octet-stream";
                     Response.AddHeader("Content-Disposition", "attachment;filename=" + (Request.UserAgent.ToLower().IndexOf("msie") > -1 ? Server.UrlPathEncode(fileInfo.Name) : fileInfo.Name)); 
                     Response.TransmitFile(oldname);
                     Response.End();
                     return;
                    #endregion
                    break;
                case "":
                    #region 列表OK
                    litBody.Text = List();
                    #endregion
                    break;
            }
            #endregion
        }
        public long GetDirectoryLength(string dirPath)
        {
            long len = 0;
            DirectoryInfo di = new DirectoryInfo(dirPath);
            foreach (FileInfo fi in di.GetFiles())
            {
                len += fi.Length;
            }
            DirectoryInfo[] dis = di.GetDirectories();
            if (dis.Length > 0)
            {
                for (int i = 0; i < dis.Length; i++)
                {
                    len += GetDirectoryLength(dis[i].FullName);
                }
            }
            return len;
        }
        private void getFileHTML(StringBuilder sb, string name)
        {
          
            string _path = "../upload/" + (sitefolder.Length > 0 ? sitefolder + "/" : "") + basefolder + (path.Length > 0 ? "/" + path : "") + "/" + name;
            FileInfo info = new FileInfo(Server.MapPath(_path));
            eFileInfo fi = new eFileInfo(name);
            sb.Append("<a ext=\"." + fi.Extension.ToLower() + "\" href=\"" + aspxFile + "?act=download" + (AppItem.Length > 0 ? "&AppItem=" + AppItem : "&ModelID=" + ModelID) + "&path=" + (path.Length > 0 ? path + "/" : path) + "&name=" + Server.UrlEncode(name) + "\" target=\"_blank\" class=\"copypath\" onmousedown=\"contextmenu(event,this,2,'" + name + "');\" title=\"" + name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", info.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", info.LastWriteTime) + "&#10;大小：" + eBase.getFileSize(info.Length) + "\">\r\n");
            sb.Append("<dl>\r\n");
            //sb.Append("<dt><img src=\"../images/excel.png\" /></dt>\r\n");
            sb.Append("<dt class=\"excel\"></dt>\r\n");
            sb.Append("<dd>" + name + "</dd>\r\n");
            sb.Append("</dl>\r\n");
            sb.Append("</a>\r\n");
        }
        private string getFiles()
        {
            StringBuilder sb = new StringBuilder();
            System.IO.DirectoryInfo dinfo = new DirectoryInfo(basePath);
            foreach (DirectoryInfo folder in dinfo.GetDirectories())
            {
                sb.Append("<a ext=\"\" href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&path=" + (path.Length > 0 ? path + "/" : path) + folder.Name.ToString() + "\" onmousedown=\"contextmenu(event,this,1,'" + folder.Name + "');\" title=\"" + folder.Name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", folder.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", folder.LastWriteTime) + "&#10;大小：" + eBase.getFileSize(GetDirectoryLength(folder.FullName)) + "\">\r\n");
                sb.Append("<dl>\r\n");
                sb.Append("<dt class=\"folder\"></dt>\r\n");
                sb.Append("<dd>" + folder.Name + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");
            }
            foreach (FileInfo file in dinfo.GetFiles())
            {
                string ext = Path.GetExtension(file.Name).ToLower();
                if (".xlsx".IndexOf(ext) == -1) continue;
                getFileHTML(sb, file.Name);
            }
            sb.Append("<div class=\"clear\"></div>\r\n");
            return sb.ToString();
        }
        private string List()
        {
            StringBuilder sb = new StringBuilder();
            //sb.Append("<div>当前位置：");
           
            if (path.Length > 0)
            {
                //sb.Append("<a href=\"" + aspxFile + "?modelid=" + ModelID + "\">根目录</a>");
                litNav.Text = "<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">" + model.ModelInfo["MC"].ToString() + "</a>";
                litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">根目录</a>";
                string[] arr = path.Split("/".ToCharArray());
                string tmp = "";
                for (int i = 0; i < arr.Length; i++)
                {
                    if (i > 0) tmp += "/";
                    tmp += arr[i];
                    if (i == arr.Length - 1)
                    {
                        //sb.Append(" / " + arr[i]);
                    }
                    else
                    {
                        //sb.Append(" / <a href=\"" + aspxFile + "?modelid=" + ModelID + "&path=" + tmp + "\">" + arr[i] + "</a>");
                    }
                    litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&path=" + tmp + "\">" + arr[i] + "</a>";
                }
            }
            else
            {
                //sb.Append("根目录");
                litNav.Text = "<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">" + model.ModelInfo["MC"].ToString() + "</a>";
                litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">根目录</a>";
            }

            if (model.Power["new"] || model.Power["upload"])
            {
                sb.Append("<div class=\"filemanage_tool\" style=\"margin-tottom:8px;\">");
                if (model.Power["new"])
                {
                    sb.Append("<a href=\"javascript:;\" class=\"ico addfolder\" onclick=\"file_newFolder();\" title=\"新建文件夹\"></a>");
                    //sb.Append("<a href=\"javascript:;\" class=\"ico addfile\" onclick=\"file_newFile();\" title=\"新建文件\"></a>");
                }
                if (model.Power["upload"])
                {
                    sb.Append("<a href=\"javascript:;\" class=\"ico upload\" title=\"上传文件\"><input type=\"file\" title=\"上传文件\" class=\"file\" id=\"imgFile\" name=\"imgFile\" badexts=\"" + eConfig.getDangerExtensions() + "\" accept=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel\" onchange=\"file_upload(this);\" multiple=\"multiplt\" /></a>");
                }
                sb.Append("</div>");
            }

            sb.Append("<div id=\"filemanage_files\" class=\"filemanage_files\" oncontextmenu=\"return false;\">");            
            sb.Append(getFiles());
            sb.Append("</div>");
            return sb.ToString();
        }
        public void FileToZip(string FromFile, string toZipFile)
        {
            using (ZipFile zip = ZipFile.Create(toZipFile))
            {
                zip.BeginUpdate();
                zip.Add(FromFile, System.IO.Path.GetFileName(FromFile));
                zip.CommitUpdate();
            }
        }
        public void FolderToZip(string folderPath, string toZipFile)
        {
            using (ZipFile zip = ZipFile.Create(toZipFile))
            {
                zip.NameTransform = new ZipNameTransform(basePath);
                zip.BeginUpdate();
                addFolder(folderPath, zip);
                zip.CommitUpdate();
            }
        }
        private void addFolder(string folderPath, ZipFile zip)
        {
            zip.AddDirectory(folderPath);
            DirectoryInfo di = new DirectoryInfo(folderPath);
            foreach (FileInfo item in di.GetFiles())
            {
                zip.Add(item.FullName);
            }
            foreach (DirectoryInfo item in di.GetDirectories())//遍历出所有目录
            {
                addFolder(item.FullName, zip);
            }
        }
    }
}